#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

from Crypto.Cipher import AES
import base64, datetime, json, requests, time
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256, SHA1, SHA, SHA512, MD5
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5
from random import Random
from django.db.models import Count, Sum, Max, Min, Avg
from decimal import Decimal

from merchants.models import MerchantBill, MerchantSettlementRecord, MerchantChannel, MerchantBillSettlementRecord
from speeds.models import SpeedMerchantAuthDraw

BLOCK_SIZE = AES.block_size
pad = lambda s: s + (BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]


def random_str(randomlength=32):
    strs = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        strs += chars[random.randint(0, length)]
    return strs


class AESCipher:

    def __init__(self, secretkey, iv):
        self.key = secretkey
        self.iv = iv

    def encrypt(self, text):

        text = pad(text).encode()
        cipher = AES.new(key=base64.b64decode(self.key.encode()), mode=AES.MODE_CBC, IV=self.iv.encode())
        encrypted_text = cipher.encrypt(text)
        return base64.b64encode(encrypted_text).decode('utf-8')

    def decrypt(self, encrypted_text):

        encrypted_text = base64.b64decode(encrypted_text)
        cipher = AES.new(key=base64.b64decode(self.key.encode()), mode=AES.MODE_CBC, IV=self.iv.encode())
        decrypted_text = cipher.decrypt(encrypted_text)
        return unpad(decrypted_text).decode('utf-8')


def get_message(data_dict, message):

    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
    return message + "&" + params_str


class RSACipher:

    def __init__(self, pubkey, privkey):
        self.pubkey = self._format_public_key(pubkey)  # 密钥
        self.privkey = self._format_private_key(privkey)  # 偏移量

    def _format_private_key(self, private_key):
        __pem_begin = '-----BEGIN RSA PRIVATE KEY-----\n'
        __pem_end = '\n-----END RSA PRIVATE KEY-----'
        if not private_key.startswith(__pem_begin):
            private_key = __pem_begin + private_key
        if not private_key.endswith(__pem_end):
            private_key = private_key + __pem_end
        return private_key

    def _format_public_key(self, public_key):
        __pem_begin = '-----BEGIN RSA PUBLIC KEY-----\n'
        __pem_end = '\n-----END RSA PUBLIC KEY-----'
        if not public_key.startswith(__pem_begin):
            public_key = __pem_begin + public_key
        if not public_key.endswith(__pem_end):
            public_key = public_key + __pem_end
        return public_key

    def rsaEncrypt(self, message):
        msg = message.encode('utf-8')
        rsakey = RSA.importKey(self.pubkey)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        cipher_text = base64.b64encode(cipher.encrypt(msg))
        return cipher_text

    def rsaDecrypt(self, result):
        msg = result.encode('utf-8')
        rsakey = RSA.importKey(self.privkey)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        text = cipher.decrypt(base64.b64decode(msg), b'ERROR')
        return text.decode('utf-8')

    def sign(self, message):
        rsakey = RSA.importKey(self.privkey)
        cipher = sign_PKCS1_v1_5.new(rsakey)
        rand_hash = SHA256.new()
        rand_hash.update(message.encode())
        signature = cipher.sign(rand_hash)
        return str((base64.b64encode(signature)), encoding="utf-8")

    def verify(self, message, signature):
        key = RSA.importKey(self.pubkey)
        rand_hash = SHA256.new()
        rand_hash.update(message.encode())
        verifier = sign_PKCS1_v1_5.new(key)
        if not verifier.verify(rand_hash, base64.b64decode(signature)):
            return False
        else:
            return True


def query_transettletoday(s_merInId):
    publicKey = '''MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0CzGDOwz5IcPA+/EhLt98G7EKUhE90U1v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8WmLPfNNX3U2MS8zJSxdgvvbMBtPiMlWf7L2H5TNLm/2yr0+iYK8DBV96RdxBwCkRnUatK4R25jA1Elr1a6cqw3hLAGhQKBgQC6WYY5nDE6YTKERk4ZfL4Up3TDWn31JgxhWpStIo0sevb57iepkG7JX3f8n81H4LI3j1lSyq4y+eKCJ+ZVOGVJFvgbBVzS8SVQybvKe3hX57x4aPhXDxVadlQQwHL2KBMoydc66m4Y6BylqeerRzL9fN1xVC183Si+2tnSOf05WwKBgCc+5EC2NUeE/x02JBoAdpi/0vZyJcgUMAYkD339P+ZsBzjpZQbq0HnHB5r21bbSlpdc2LL1MzQa+qWbGaJlQG2wL2e3foD3diEzOnGkMGUlly42OdjfYiySEWgAv7Bggej6dLEvu0Wl+Uvu+spaqVXVAA92V0pDqN+tkua8h7KBAoGAU4gHu9FA29tv6o0dOx2IkveRRnRM29PnXshcttMzFwozpUrU6pQ8pPWvckUrnpmhKXiPYKZLubv7hb5e6Dp0ZHPwWSRpPIEt6e3TyOrZwgW1nP/ouhWfy8IY4r1xitfh5rm7ScSF/5IkLTphB4zN1YTgOomyLjNwrUSquSqXUNsCgYEAx0Nbfq+AzCS3fgm3d0Rh2LMjzmr+SdJa6LVOPiRORl9g4kvUVo5oRmFTxMMgJFEu+2e1yKCzx9P8byN2X90ggHw64bnnfNtybFo7LWfK//CDWeF2pKCYFHLI2etr1in7NKpWe6TpGtfzQwc1cQG7dj3UEHhmL37qXu4hCsx0KDs='''
    url = 'https://rjp.ruiyinxin.com/nms/ims/tranSt/tranStTodayList'
    reqTime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    aesKey = random_str(43) + '='
    ivParam = random_str(16)
    encryptKey_json = json.dumps({"aesKey": aesKey, "ivParam": ivParam})
    aes_cipher = AESCipher(aesKey, ivParam)
    rsa_cipher = RSACipher(publicKey, aceessPrivateKey)
    info = aes_cipher.encrypt(json.dumps({"s_merInId": s_merInId}))
    message = f'accessId=000000000000000&reqTime={reqTime}&ivParam={ivParam}&s_merInId={s_merInId}'
    sign = rsa_cipher.sign(message)
    encryptKey = rsa_cipher.rsaEncrypt(encryptKey_json)
    body = {
        "accessId": "000000000000000",
        "encryptKey": encryptKey,
        "sign": sign,
        "info": info,
        "reqTime": reqTime
    }
    response = requests.post(url=url, data=body)
    response_data = response.json()
    reaponse_reqTime = response_data['reqTime']
    reaponse_encryptKey = json.loads(rsa_cipher.rsaDecrypt(response_data['encryptKey']))
    response_message = f'accessId={response_data["accessId"]}&reqTime={reaponse_reqTime}&ivParam={reaponse_encryptKey["ivParam"]}'
    response_aes_cipher = AESCipher(reaponse_encryptKey['aesKey'], reaponse_encryptKey['ivParam'])
    reaponse_info = json.loads(response_aes_cipher.decrypt(response_data['info']))
    return reaponse_info


def query_merinid(s_merInId):
    publicKey = '''MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0CzGDOwz5IcPA+/EhLt98G7EKUhE90U1v162xqXDzL8t+2Ok+iBnZQFFqWNB6gnID7GzaUVrDaNQX1vFLcCvhCgMgvOa973xFjeDJPXF/xUQboagWkZb8EGxiyympbN8SO4mey9Ldn9EX3m+yKuqvCrJTEKK0Gqg/Y/Dr3oCzC8KdesAb6x/ZTccsyHVPrzZ5LUkIMFVb4QVAFcI6/aa3G4GpZwLdsxrUnJ1k8kjYgx0GfC6Z0M665Z+lZpt+bQjk/ZwEHkbAjleREz/DPiefBbfGP/UKgLjcRxTN8mPHzT1SHw1U8hV4zFyJkGAOL+b8Bg4LAuHwveoeMYmf3kGeQIDAQAB'''
    privateKey = '''MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDQLMYM7DPkhw8D78SEu33wbsQpSET3RTW/XrbGpcPMvy37Y6T6IGdlAUWpY0HqCcgPsbNpRWsNo1BfW8UtwK+EKAyC85r3vfEWN4Mk9cX/FRBuhqBaRlvwQbGLLKals3xI7iZ7L0t2f0Rfeb7Iq6q8KslMQorQaqD9j8OvegLMLwp16wBvrH9l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h5rm7ScSF/5IkLTphB4zN1YTgOomyLjNwrUSquSqXUNsCgYEAx0Nbfq+AzCS3fgm3d0Rh2LMjzmr+SdJa6LVOPiRORl9g4kvUVo5oRmFTxMMgJFEu+2e1yKCzx9P8byN2X90ggHw64bnnfNtybFo7LWfK//CDWeF2pKCYFHLI2etr1in7NKpWe6TpGtfzQwc1cQG7dj3UEHhmL37qXu4hCsx0KDs='''
    url = 'https://rjp.ruiyinxin.com/nms/ims/merch/getMerInId'
    reqTime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    aesKey = random_str(43) + '='
    ivParam = random_str(16)
    encryptKey_json = json.dumps({"aesKey": aesKey, "ivParam": ivParam})
    aes_cipher = AESCipher(aesKey, ivParam)
    rsa_cipher = RSACipher(publicKey, aceessPrivateKey)
    info = aes_cipher.encrypt(json.dumps({"merId": s_merInId}))
    message = f'accessId=000000000000000&reqTime={reqTime}&ivParam={ivParam}&merId={s_merInId}'
    sign = rsa_cipher.sign(message)
    encryptKey = rsa_cipher.rsaEncrypt(encryptKey_json)
    body = {
        "accessId": "000000000000000",
        "encryptKey": encryptKey,
        "sign": sign,
        "info": info,
        "reqTime": reqTime
    }
    response = requests.post(url=url, data=body)
    response_data = response.json()
    reaponse_reqTime = response_data['reqTime']
    reaponse_encryptKey = json.loads(rsa_cipher.rsaDecrypt(response_data['encryptKey']))
    response_message = f'accessId={response_data["accessId"]}&reqTime={reaponse_reqTime}&ivParam={reaponse_encryptKey["ivParam"]}'
    response_aes_cipher = AESCipher(reaponse_encryptKey['aesKey'], reaponse_encryptKey['ivParam'])
    reaponse_info = json.loads(response_aes_cipher.decrypt(response_data['info']))
    return reaponse_info['result']['merInId']


def query_transettle(s_merInId, s_tranDates, s_tranDatee):
    '''
    publicKey 服务端公钥
    privateKey 服务端私钥
    accessPublicKey 客户端公钥
    aceessPrivateKey 客户端私钥
    '''
    publicKey = '''MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0CzGDOwz5I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PEZw2Chq0SJCgh7y9VXfc8WmLPfNNX3U2MS8zJSxdgvvbMBtPiMlWf7L2H5TNLm/2yr0+iYK8DBV96RdxBwCkRnUatK4R25jA1Elr1a6cqw3hLAGhQKBgQC6WYY5nDE6YTKERk4ZfL4Up3TDWn31JgxhWpStIo0sevb57iepkG7JX3f8n81H4LI3j1lSyq4y+eKCJ+ZVOGVJFvgbBVzS8SVQybvKe3hX57x4aPhXDxVadlQQwHL2KBMoydc66m4Y6BylqeerRzL9fN1xVC183Si+2tnSOf05WwKBgCc+5EC2NUeE/x02JBoAdpi/0vZyJcgUMAYkD339P+ZsBzjpZQbq0HnHB5r21bbSlpdc2LL1MzQa+qWbGaJlQG2wL2e3foD3diEzOnGkMGUlly42OdjfYiySEWgAv7Bggej6dLEvu0Wl+Uvu+spaqVXVAA92V0pDqN+tkua8h7KBAoGAU4gHu9FA29tv6o0dOx2IkveRRnRM29PnXshcttMzFwozpUrU6pQ8pPWvckUrnpmhKXiPYKZLubv7hb5e6Dp0ZHPwWSRpPIEt6e3TyOrZwgW1nP/ouhWfy8IY4r1xitfh5rm7ScSF/5IkLTphB4zN1YTgOomyLjNwrUSquSqXUNsCgYEAx0Nbfq+AzCS3fgm3d0Rh2LMjzmr+SdJa6LVOPiRORl9g4kvUVo5oRmFTxMMgJFEu+2e1yKCzx9P8byN2X90ggHw64bnnfNtybFo7LWfK//CDWeF2pKCYFHLI2etr1in7NKpWe6TpGtfzQwc1cQG7dj3UEHhmL37qXu4hCsx0KDs='''
    url = 'https://rjp.ruiyinxin.com/nms/ims/tranSt/tranStList'
    reqTime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    aesKey = random_str(43) + '='
    ivParam = random_str(16)
    encryptKey_json = json.dumps({"aesKey": aesKey, "ivParam": ivParam})
    aes_cipher = AESCipher(aesKey, ivParam)
    rsa_cipher = RSACipher(publicKey, aceessPrivateKey)
    info = aes_cipher.encrypt(json.dumps({"s_merInId": s_merInId, "s_tranDates": s_tranDates, "s_tranDatee": s_tranDatee}))
    message = f'accessId=000000000000000&reqTime={reqTime}&ivParam={ivParam}&s_merInId={s_merInId}&s_tranDatee={s_tranDatee}&s_tranDates={s_tranDates}'
    sign = rsa_cipher.sign(message)
    encryptKey = rsa_cipher.rsaEncrypt(encryptKey_json)
    body = {
        "accessId": "000000000000000",
        "encryptKey": encryptKey,
        "sign": sign,
        "info": info,
        "reqTime": reqTime
    }
    response = requests.post(url=url, data=body)
    response_data = response.json()
    reaponse_reqTime = response_data['reqTime']
    reaponse_encryptKey = json.loads(rsa_cipher.rsaDecrypt(response_data['encryptKey']))
    response_message = f'accessId={response_data["accessId"]}&reqTime={reaponse_reqTime}&ivParam={reaponse_encryptKey["ivParam"]}'
    response_aes_cipher = AESCipher(reaponse_encryptKey['aesKey'], reaponse_encryptKey['ivParam'])
    reaponse_info = json.loads(response_aes_cipher.decrypt(response_data['info']))
    return reaponse_info


def synchronous_settlerecord():
    print('%s: synchronous_settlerecord' % time.ctime())
    date_now = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
    queryset = MerchantChannel.objects.filter(merchant__merchantbill__bill_state__in=[1, 5], channel_id=2, merchant__merchantbill__receipts_time__lt=date_now).distinct()
    print('应结算商户数', len(queryset))
    # queryset = MerchantChannel.objects.filter(merchant_id=720)
    for query in queryset:
        merchant_id = query.merchant_id
        channel_mchid = query.channel_mchid
        result = query_transettletoday(channel_mchid)['result']
        # result = query_transettle(channel_mchid)['result']
        if result:
            result = result['list']
            for i in result:
                if i['settleType'] =='16':
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if create:
                        # if i['status'] == '出款成功':
                        settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                        merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lt=settlement_time_before)
                        for merchantbill in merchantbill_set:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = merchantbill.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                            print(f'{merchantbill.id}正常结算:{i["status"]}')
                        merchantbill_set.update(
                            account_name=i['cardName'],
                            account_bank=i['bankName'],
                            account_number=i['cardNo'],
                            settlement_time=settlement_time,
                            settlement_record_id=instance.id,
                            bill_state=instance.status,
                        )
                elif i['settleType'] =='02':
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['settle_type'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if create:
                        # if i['status'] == '出款成功':
                        settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                        merchantbill_set = MerchantBill.objects.filter(bill_state=5, merchant_id=merchant_id, receipts_time__lt=settlement_time_before)
                        for merchantbill in merchantbill_set:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = merchantbill.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                            print(f'{merchantbill.id}退汇结算:{i["status"]}')
                        merchantbill_set.update(
                            account_name=i['cardName'],
                            account_bank=i['bankName'],
                            account_number=i['cardNo'],
                            settlement_time=settlement_time,
                            settlement_record_id=instance.id,
                            bill_state=instance.status,
                        )
    return '------------结束------------'


def check_try():
    instance = SpeedMerchantAuthDraw.objects.filter(appid='wx1cdf14a52b6b487b', platform=1, payment_status=1).update(payment_status=3)


def synchronous_settlerecord1():
    print('%s: synchronous_settlerecord1' % time.ctime())
    date_now = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
    # queryset = MerchantChannel.objects.filter(merchant__merchantbill__bill_state=1, channel_id=2).distinct()
    queryset = MerchantBill.objects.filter(bill_state=1).order_by('receipts_time')
    print('应结算商户数', len(queryset))
    # queryset = MerchantChannel.objects.filter(merchant_id=720)
    for query in queryset:
        print(query.id)
        merchant_id = query.merchant_id
        channel_mchid = MerchantChannel.objects.filter(merchant_id=merchant_id, channel_id=2)
        if not channel_mchid:
            continue
        channel_mchid = channel_mchid.first().channel_mchid
        s_tranDates = (query.receipts_time + datetime.timedelta(days=1)).strftime("%Y%m%d")
        result = query_transettle(channel_mchid, s_tranDates, s_tranDates)['result']
        # result = query_transettle(channel_mchid)['result']
        if result:
            result = result['list']
            for i in result:
                if i['settleType'] in ['16', '10']:
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['level_id'] = query.merchant.level_id
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if Decimal(str(instance.amount)) == query.payable_amount:
                        relations_data = {}
                        relations_data['settlement_record_id'] = instance.id
                        relations_data['bill_id'] = query.id
                        MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                        print(f'{query.id}正常结算:{i["status"]}')
                        query.account_name = i['cardName']
                        query.account_bank = i['bankName']
                        query.account_number = i['cardNo']
                        query.settlement_time = settlement_time
                        query.settlement_record_id = instance.id
                        query.bill_state = instance.status
                        query.settlement_amount = instance.amount
                        query.save()
                        # if i['status'] == '出款成功':
                        # settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                        # merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lt=settlement_time_before)
                        # for merchantbill in merchantbill_set:
                        #     relations_data = {}
                        #     relations_data['settlement_record_id'] = instance.id
                        #     relations_data['bill_id'] = merchantbill.id
                        #     MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                        #     print(f'{merchantbill.id}正常结算:{i["status"]}')
                        # merchantbill_set.update(
                        #     account_name=i['cardName'],
                        #     account_bank=i['bankName'],
                        #     account_number=i['cardNo'],
                        #     settlement_time=settlement_time,
                        #     settlement_record_id=instance.id,
                        #     bill_state=instance.status,
                        # )
                elif i['settleType'] =='02':
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['settle_type'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if Decimal(str(instance.amount)) == query.payable_amount:
                        relations_data = {}
                        relations_data['settlement_record_id'] = instance.id
                        relations_data['bill_id'] = query.id
                        MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                        print(f'{query.id}正常结算:{i["status"]}')
                        query.account_name = i['cardName']
                        query.account_bank = i['bankName']
                        query.account_number = i['cardNo']
                        query.settlement_time = settlement_time
                        query.settlement_record_id = instance.id
                        query.bill_state = instance.status
                        query.settlement_amount = instance.amount
                        query.save()
    return '------------结束------------'


def synchronous_settlerecord2():
    print('%s: synchronous_settlerecord1' % time.ctime())
    date_now = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
    # queryset = MerchantChannel.objects.filter(merchant__merchantbill__bill_state=1, channel_id=2).distinct()
    queryset = MerchantBill.objects.filter(bill_state=1).order_by('receipts_time')
    print('应结算商户数', len(queryset))
    # queryset = MerchantChannel.objects.filter(merchant_id=720)
    for query in queryset:
        query = MerchantBill.objects.get(id=query.id)
        if query.bill_state != 1:
            continue
        print(query.id)
        merchant_id = query.merchant_id
        channel_mchid = MerchantChannel.objects.filter(merchant_id=merchant_id, channel_id=2)
        if not channel_mchid:
            continue
        channel_mchid = channel_mchid.first().channel_mchid
        days = 1
        # while True:
        s_tranDates = (query.receipts_time + datetime.timedelta(days=days)).strftime("%Y%m%d")
        s_tranDatee = (query.receipts_time + datetime.timedelta(days=9)).strftime("%Y%m%d")
        result = query_transettle(channel_mchid, s_tranDates, s_tranDatee)['result']
            # result = query_transettle(channel_mchid)['result']
            # if result:
            #     break
            # # print(days)
            # if days == 10:
            #     break
            # days += 1
        if result:
            result = result['list']
            for i in result:
                if i['settleType'] in ['16', '10', '02']:
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['level_id'] = query.merchant.level_id
                    settlerecord_data['channel_id'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    settlement_time_before = settlement_time + datetime.timedelta(days=-4)
                    receipts_time__gte = settlement_time + datetime.timedelta(days=-7)
                    merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lte=settlement_time_before, receipts_time__gte=receipts_time__gte)
                    total_amount = merchantbill_set.aggregate(Sum('payable_amount'))['payable_amount__sum']
                    if Decimal(str(instance.amount)) == total_amount:
                        for merchantbill in merchantbill_set:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = merchantbill.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                            print(f'{merchantbill.id}正常结算:{i["status"]}')
                        merchantbill_set.update(
                            account_name=i['cardName'],
                            account_bank=i['bankName'],
                            account_number=i['cardNo'],
                            settlement_time=settlement_time,
                            settlement_record_id=instance.id,
                            bill_state=instance.status,
                        )
                # elif i['settleType'] =='02':
                #     if i['status'] == '出款中':
                #         continue
                #     settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                #     settlerecord_data = {}
                #     settlerecord_data['merchant_id'] = merchant_id
                #     settlerecord_data['account_name'] = i['cardName']
                #     settlerecord_data['account_bank'] = i['bankName']
                #     settlerecord_data['account_number'] = i['cardNo']
                #     settlerecord_data['amount'] = i['amt']
                #     settlerecord_data['settlement_time'] = settlement_time
                #     settlerecord_data['fail_reason'] = i['failReason']
                #     settlerecord_data['settle_type'] = 2
                #     if i['status'] == '出款成功':
                #         settlerecord_data['status'] = 3
                #     elif i['status'] == '出款中':
                #         settlerecord_data['status'] = 2
                #     else:
                #         settlerecord_data['status'] = 5
                #     instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                #     if create:
                #         settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                #         merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lt=settlement_time_before)
                #         total_amount = merchantbill_set.aggregate(Sum('payable_amount'))['payable_amount__sum']
                #         if instance.amount == total_amount:
                #             for merchantbill in merchantbill_set:
                #                 relations_data = {}
                #                 relations_data['settlement_record_id'] = instance.id
                #                 relations_data['bill_id'] = merchantbill.id
                #                 MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                #                 print(f'{merchantbill.id}正常结算:{i["status"]}')
                #             merchantbill_set.update(
                #                 account_name=i['cardName'],
                #                 account_bank=i['bankName'],
                #                 account_number=i['cardNo'],
                #                 settlement_time=settlement_time,
                #                 settlement_record_id=instance.id,
                #                 bill_state=instance.status,
                #             )
    return '------------结束------------'


if __name__ == '__main__':
    synchronous_settlerecord2()